<?php
class Myutility_Authlist
{
	private $_role;     //角色
	private $_resource; //资源
	private $_action;   //动作
	private $_acl;
	
	public function __construct($role,$res,$ac) 
	{
		$this->_role = $role;
		$this->_resource = $res;
		$this->_action = $ac;
	}
	
	public function initAcl()
	{
		$acl = new Zend_Acl();
		$acArr = $this->setParam();
		$acl->addRole(new Zend_Acl_Role($this->_role));
		foreach ($this->_resource as $resource) {
			$acl->add(new Zend_Acl_Resource($resource));
		}
		foreach ($this->_resource as $resource) {
			$acl->allow($this->_role,$resource,$acArr[$resource]);
		}
		$this->_acl = $acl;
	}
	
	public function saveAcl()
	{
		$acl = $this->_acl;
		$strAcl = serialize($acl);
		//因为是demo就没有创建数据库，所以就把acl对象保存到一个文本文件中，
		//如果是数据库可以保存到各用户的某一个字段中
		$fp = fopen('../application/object.txt','w');
		if($fp) fwrite($fp, $strAcl, strlen($strAcl));
		
	}
	
	public function setParam()
	{
		$action = $this->_action;
		foreach ($action as $key => $value) {
			$rowArr = explode('_', $value);
			$acArr[$rowArr[0]][$key] = $rowArr[1]; 
		}
		return $acArr;
	}
	
	public function isAllow()
	{
		$acl = unserialize(file_get_contents('../application/object.txt'));
		//此处admin是为了测试而使用的一个字符串常量，正式使用可用session变量代替
		//echo $acl->has('member') ? "yes" : "no";
		if(!$acl->has($this->_resource)) 
			$acl->add(new Zend_Acl_Resource($this->resource));
		$isallow = $acl->isAllowed($this->_role, $this->_resource, $this->_action);
		return $isallow;
	}
}
?>